//
//  StatusPictureView.swift
//  HMWeibo08
//
//  Created by 唐万超 on 15/8/3.
//  Copyright © 2015年 唐万超. All rights reserved.
//

import UIKit
import SDWebImage

/// 可重用 cell 标示符
private let statusPictureViewCellID = "statusPictureViewCellID"

class StatusPictureView: UICollectionView {
    
    /// 微博数据
    var statuses: Status? {
        didSet {
            sizeToFit()
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        
       return picViewSize()
    }
    
    /// 计算视图大小
    private func picViewSize() -> CGSize {
    
        // 常量准备
        let itemSize = CGSize(width: 90, height: 90)
        
        let margin: CGFloat = 10
        
        // 每一行最多显示的数据
        let rowCount = 3
        
        pictureLayout.itemSize = itemSize
        
        // 1. 根据图片数量计算视图大小
        let count = statuses?.picURLs?.count ?? 0
        
        // 1> 没有图片
        if count == 0 {
            return CGSizeZero
        }
        
        // 2> 1张图片
        if count == 1 {
           
            let key = statuses!.picURLs![0].absoluteString
            
            // 通过SDWebImage读取磁盘缓存的图片
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            
            // 如果图像不存在的默认大小
            var size = CGSize(width: 150, height: 120)
            
            if image != nil {
                
                size = image.size
            }
            
            // 进一步判断图片的尺寸，防止过宽过窄
            size.width = size.width < 40 ? 40 : size.width
            size.width = size.width > UIScreen.mainScreen().bounds.width ? 150 : size.width
            
            pictureLayout.itemSize = size
            
            return size
        }
        
        // 3> 4张图片 2 * 2
        if count == 4 {
            let w = itemSize.width * 2 + margin
            
            return CGSize(width: w, height: w)
        }
        
        // 4> 其他
        /**
        2, 3
        5, 6
        7, 8, 9
        */
        // 计算行数
        let row = (count - 1) / rowCount + 1
        let w = itemSize.width * CGFloat(rowCount) + margin * CGFloat(rowCount - 1)
        let h = itemSize.height * CGFloat(row) + margin * CGFloat(row - 1)
        
        return CGSize(width: w, height: h)
        
    }

    /// 图片布局
    private let pictureLayout = UICollectionViewFlowLayout()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: pictureLayout)
        
        backgroundColor = UIColor.clearColor()
        
        // 设置代理
        self.dataSource = self
        
        // 注册可重用的cell
        self.registerClass(StatusPictureViewCell.self, forCellWithReuseIdentifier: statusPictureViewCellID)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    

}

// 在 swift 中，协议同样可以通过 extension 来写，可以将一组协议方法，放置在一起，便于代码维护和阅读！
extension StatusPictureView: UICollectionViewDataSource {

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return statuses?.picURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(statusPictureViewCellID, forIndexPath: indexPath) as! StatusPictureViewCell
        
        //cell.backgroundColor = UIColor.redColor()
        // 设置图片的URL
        cell.imageURL = statuses!.picURLs![indexPath.item]
        
        return cell
        
    }
}

//  collectionView的cell
class StatusPictureViewCell: UICollectionViewCell {

    var imageURL: NSURL? {
        didSet {
            iconView.sd_setImageWithURL(imageURL)
        }
    }
    
    // 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 设置UI
    private func setupUI() {
    
        // 添加控件
        contentView.addSubview(iconView)
        // 设置约束
        iconView.ff_Fill(contentView)
    }
    
    // MARK: 懒加载控件
    private lazy var iconView: UIImageView = {
    
        let iv = UIImageView()
        
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        
        iv.clipsToBounds = true
        
        return iv
    }()
    
}

